package com.example.smartg.ui.weixin;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.smartg.LoginNavActivity;
import com.example.smartg.R;

import okhttp3.Call;
import okhttp3.Response;

import com.example.smartg.HttpUtil;
import com.example.smartg.R;
import com.example.smartg.SmartGMainActivity;
import com.example.smartg.SpUtils;
import com.example.smartg.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import com.bumptech.glide.Glide;

public class WeixinScanFragment extends Fragment {

    public View view;
    private String key;
    private int try_times = 0;
    //加上计时器
    private Timer mTimer; // 计时器，每2秒执行一次任务
    private MyTimerTask mTimerTask; // 计时任务，判断是否未操作时间到达ns

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_weixin_scan, container, false);
        }
        ImageView imageView = (ImageView) view.findViewById(R.id.return_to_home);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SmartGMainActivity.class);
                startActivity(intent);
            }
        });
        ImageView imageView1 = (ImageView) view.findViewById(R.id.scan_code_image);
        imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                create_scan_code_image();
            }
        });
        create_scan_code_image();
        return view;
    }

    @Override
    public void onDestroyView() {
        stopTimer();
        super.onDestroyView();
    }


    public void get_token(String key) {
        String url = "http://10.2.47.115/gm_user/get_smartg_token";
        //实例化
        HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();
        try {
            json.put("key", key);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.error(getActivity(), "服务器出错！");
                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                Log.e("responsedata", responsedata);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");
                    if (code == 20000) {
                        JSONObject data = jsonObject.optJSONObject("data");
                        String token = data.optString("token");
                        String user_name = data.optString("name");
                        // 记住用户信息到SharedPreferences
                        SpUtils.putString(getActivity(), "token", token);
                        SpUtils.putString(getActivity(), "user_name", user_name);
                        stopTimer();
                        // 跳转到管理员界面？还是跳转到上一界面?
                        getActivity().finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void create_scan_code_image() {
        key = UUID.randomUUID().toString().replace("-","");
        String url = "http://10.2.47.115/gm_user/get_agv_mini_code?page=packageB/pages/package/smart_box/scan_login/scan_login&env_version=release&_id=" + key;
        Log.e("url",url);
        try_times = 0;
        ImageView imageView = (ImageView) view.findViewById(R.id.scan_code_image);
        Log.e("key",key);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Glide
                        .with(WeixinScanFragment.this)
                        .load(url)
                        .placeholder(R.drawable.loading)
                        .into(imageView);
            }
        });

        if(mTimerTask!=null){
            stopTimer();
        }
        startTimer();
    }

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            //Log.e(TAG, "计时中……");
            try_times += 1;
            if (try_times < 10) {
                get_token(key);
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.error(getActivity(), "超时，请刷新程序码后重新扫描！");
                        stopTimer();
                    }
                });
            }
        }
    }

    public void stopTimer() {
        Log.e("=1=", "主页定时任务关闭");
        mTimer.cancel();
    }

    private void startTimer() {
        Log.e("=1=", "主页定时任务启动");
        mTimer = new Timer();
        mTimerTask = new MyTimerTask();
        // 初始化上次操作时间为登录成功的时间
        // 每过1s检查一次
        mTimer.schedule(mTimerTask, 0, 3000);
        //Log.e(TAG, "登录成功开始计时");

    }
}